package net;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.List;
import java.util.Scanner;

public class MyChatServer implements PropertyChangeListener{
	private static final int MAXCLIENTS = 10;
	private List<ChatService> clients = new ArrayList<ChatService>();
	private boolean isRunning = true;
	private ServerSocket ss;
	private int port = 9099;
	Thread serverThread = null;
	
	public MyChatServer(){
		try {
			ss = new ServerSocket(port);
			start();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void start(){
		serverThread = new Thread(new Runnable(){
			public void run(){
				while(isRunning){
					try {
						Socket s = ss.accept();
						ChatService cs = new ChatService(s, MyChatServer.this);
						clients.add(cs);
						Thread t = new Thread(cs);
						t.start();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
		serverThread.start();
	}
	
	public void stop(){
		if(serverThread != null){
			isRunning = false;
			try {
				serverThread.join();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		// TODO Auto-generated method stub
		String msg = (String)evt.getNewValue();
		System.out.println(msg);
	}
	
	
	class ChatService implements Runnable{
		Socket _socket;
		InputStream in;
		OutputStream out;
		PropertyChangeListener _handler;
		boolean isAlive = true;
		
		ChatService(Socket socket, PropertyChangeListener handler){
			_socket = socket;
			_handler = handler;
		}
		
		public synchronized void sendMessage(String msg){
			try{
				out.write(msg.getBytes(Charset.forName("utf-8")));
			}catch(IOException ex){
				
			}
		}
		
		public void run(){
			try {
				out = _socket.getOutputStream();
				in = _socket.getInputStream();

				try{
					byte[] buf = new byte[512];
					int read = 0;
					while((read=in.read(buf))>=0 && isAlive){
						String msg = new String(buf, 0, read, Charset.forName("utf-8"));
						_handler.propertyChange(new PropertyChangeEvent(this, 
								"Message", "", msg));
					}
				}catch(IOException ex){
					_handler.propertyChange(new PropertyChangeEvent(this, 
							"Exception", "", ex.getMessage()));
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
